package cn.com.yinhex.util;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.log4j.Logger;

/**
 * Row处理类
 */
public class RowUtil {
  private static Logger logger = Logger.getLogger(RowUtil.class);

  /**
   * 通过存在的Row来构造Bean对象
   * 要求字段必须一致（建议数据库字段不要含下划线等符号，不要中间夹带大小写）
   * @param perFillObject
   * @param parameterMap
   * @return
   */
  public static Object toValueObject(Object perFillObject, Row row) {
    try {
      if (row == null)
        return perFillObject;

      Object key = null;
      Iterator i = row.keySet().iterator();
      while (i.hasNext()) {
        key = i.next();
        BeanUtils.setProperty(perFillObject, (String) key, row.get(key));
      }
      return perFillObject;
    } catch (Exception e) {
      logger.error("[Error to buildBean:" + perFillObject.getClass()
          + ",parameterMap:" + row + "]]", e.fillInStackTrace());
      return perFillObject;
    }
  }

  /**
   * 根据传过来的Bean对象转换到Row中
   * @param vo
   * @return
   * @throws Exception
   */
  public static Row fromValueObject(Object vo) throws Exception {
    Row row = new Row();
    Class type = vo.getClass(); // 得到Class用于进行反射处理
    Field[] fields = type.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      String name = fields[i].getName();
//      String methodName = "get" + Character.toUpperCase(name.charAt(0))+ name.substring(1);
//      Method method = type.getMethod(methodName, new Class[] {});
//      Object value = method.invoke(vo, new Object[] {});
      String value=BeanUtils.getProperty(vo, name);
      row.put(name, value);
    }
    return row;
  }

  /**
   * 检验ROW里面是否包念指定的字段值
   * @param includStr
   */
  public static boolean validInclude(Row row, String[] includStr) {
    for (String key : includStr) {
      String value = row.gets(key);
      //是否不存在或为空
      boolean validate = value != null && !"".equals(value.trim());
      if (!validate)
        return false;
    }
    return true;
  }

  /**
   * 合并两个Row,把row2的值合并到row1
   * @param row1
   * @param row2
   */
  public static void unionRow(Row row1, Row row2) {
    if (row1 == null)
      row1 = new Row();
    if(row2 != null)
      row1.putAll(row2);
  }

  /**
   * 获取指定字段的ROW,includeProperties以逗号分开的字段集
   * @param includeProperties
   */
  public static Row includeRow(Row oldRow, String includeProperties) {
    String[] include = includeProperties.split(",");
    return includeRow(oldRow, include);
  }

  /**
   * 获取指定字段的ROW,includeProperties为字段集数组
   * @param includeProperties
   */
  public static Row includeRow(Row oldRow, String[] includeProperties) {
    Row newRow = new Row();
    for (String pro : includeProperties) {
      Object o = oldRow.get(pro);
      if (o != null)
        newRow.put(pro, o);
    }
    return newRow;
  }

  /**
   * 将两个数组 组合成一个Map（用于需要按录入添加顺序来显示的场合）
   * @param keys
   * @param values
   * @return
   */
  public static Map arrayToMap(Object[] keys, Object[] values) {
    if (keys == null || values == null)
      return new LinkedMap();
    int keyLen = keys.length;
    int valLen = values.length;

    LinkedMap map = new LinkedMap();//按put顺序来存放
    for (int i = 0; i < keyLen; i++) {
      if (i < valLen)
        map.put(keys[i], values[i]);
      else
        map.put(keys[i], ""); //value的个数小于key的个数，后面的都置空值。
    }
    return map;
  }

  /**
   * 将两个数组 组合成一个Row
   * @param keys
   * @param values
   * @return
   */
  public static Row arrayToRow(Object[] keys, Object[] values) {
    Map map = arrayToMap(keys, values);
    return new Row(map);
  }
  
  /**
   * 将嵌套在row中的row展开
   * @param row
   * @param innerKeys 
   * @return
   */
  public static void unfoldInnerRow(Row row,String[] innerKeys)
  {
    if(innerKeys==null) return;
    try {
        for(String key:innerKeys)
        {
          if(row.containsKey(key))
          {
            Map map=null;
             if( (row.get(key)) instanceof Map)
                map=(Map)row.get(key);
             else map=BeanUtils.describe(row.get(key));
              row.putAll(map);
              row.remove(key);
          }
         } 
    } catch (Exception e) {
        logger.error("展开嵌套的row时异常", e);
       } 
    
  }
  
  /**
   * @param args
   */
  public static void main(String[] args) {
      
  }
}
